package com.eypg.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eypg.pojo.Productimage;
import com.eypg.service.FileUploadService;
import com.eypg.service.ProductImageService;
import com.eypg.util.Base64;
import com.eypg.util.ConfigUtil;
import com.eypg.util.StringUtil;
import com.eypg.util.Struts2Utils;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 作者ryan_song E-mail:song316@gmai.com
 * @version 创建时间：2011-3-3 下午10:12:32 类说明
 */
@Component
public class FileUploadAction extends ActionSupport {
	private static final long serialVersionUID = -6356307819518359036L;
	Log log = LogFactory.getLog(FileUploadAction.class);

	File filedata;
	String filedataContentType;
	String filedataFileName;
	String id;

	@Autowired
	FileUploadService fileUploadService;
	@Autowired
	ProductImageService productImageService;

	/**
	 * 上传文件到eypg. 解决跨域上传文件的问题.
	 * 
	 * @return
	 */
	public String updateFile() {
		if (filedata == null || StringUtil.isBlank(filedataFileName)) {
			log.error("FileUploadAction.updateImage 文件上传失败!");
			Struts2Utils.renderText("{\"err\":\"文件上传失败!filedata为空!\",\"msg\":\"}");
		}
		try {
			// 取得eypg上传文件接口url
			String uploadFileUrl = ConfigUtil.getValue("uploadFileUrl");
			if (StringUtil.isBlank(uploadFileUrl)) {
				log.error("FileUploadAction.updateImage 文件上传失败! eypg上传文件接口url为空!");
				Struts2Utils.renderText("{\"err\":\"文件上传失败! eypg上传文件接口url为空!\",\"msg\":\"}");
			}
			PostMethod filePost = new PostMethod(uploadFileUrl);
			// 通过以下方法可以模拟页面参数提交
			// filePost.setParameter("name", "中文");
			// filePost.setParameter("pass", "1234");
			Part[] parts = { new FilePart(filedataFileName, filedata) };
			filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {
				System.out.println("上传成功");
				// 上传成功
			} else {
				System.out.println("上传失败");
				// 上传失败
			}
			Struts2Utils.renderText("{\"err\":\"\",\"msg\":\""
					+ ServletActionContext.getRequest().getContextPath()
					+ "/fileUpload/showImage.action?id=" + "\"}");
			return null;
		} catch (IOException e) {
			log.error("上传文件失败!", e);
			Struts2Utils.renderJson("{\"err\":\"" + e.getMessage()
					+ "\",\"msg\":\"" + "上传文件失败!" + "\"}");
			return null;
		}
	}

	/**
	 * 上传文件到back系统.eypg无法查看.
	 * 
	 * @return
	 */
	public String updateImage() {
		if (filedata == null || StringUtil.isBlank(filedataFileName)) {
			log.error("FileUploadAction.updateImage 文件上传失败!");
		}
		File savefile = null;
		try {
			String saveRealFilePath = ServletActionContext.getRequest()
					.getSession().getServletContext().getRealPath("/")
					+ ConfigUtil.getValue("upfilefolder");
			File fileDir = new File(saveRealFilePath);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			savefile = new File(saveRealFilePath + filedataFileName);
			FileUtils.copyFile(filedata, savefile);
			System.err.println(">>>>>>>>>>>>>>>>" + savefile.length());
			Productimage productImage = new Productimage();
			productImage.setImage(Base64.encodeFile(savefile));
			String tmp = System.currentTimeMillis() + "";
			productImage.setPiProductId(Integer.parseInt(tmp));
			productImageService.addProductImage(productImage);
			if (savefile.exists()) {
				savefile.delete();
			}
			Struts2Utils.renderText("{\"err\":\"\",\"msg\":\""
					+ ServletActionContext.getRequest().getContextPath()
					+ "/fileUpload/showImage.action?id=" + tmp + "\"}");
			return null;
		} catch (IOException e) {
			log.error("上传文件失败!", e);
			Struts2Utils.renderJson("{\"err\":\"" + e.getMessage()
					+ "\",\"msg\":\"" + "上传文件失败!" + "\"}");
			return null;
		}
	}

	/**
	 * 返回解密后的图片文件,用于页面显示. 已不再使用.
	 * 
	 * @return
	 */
	public String showImage() {
		if (StringUtil.isBlank(id)) {
			log.error("图片id为空!");
			return null;
		}
		String image = productImageService.loadProductImageById(id);
		if (StringUtil.isBlank(image)) {
			log.error("未找到图片!");
			return null;
		}
		ServletOutputStream out = null;
		InputStream in = null;
		byte[] bytes;
		try {
			javax.servlet.http.HttpServletResponse response = ServletActionContext
					.getResponse();
			// 二进制输出流
			response.setContentType("multipart/form-data");
			// 得到输出流
			out = response.getOutputStream();
			bytes = Base64.decode(image);
			out.write(bytes);
			// 强制刷新输出流
			out.flush();
		} catch (Exception e) {
			log.error("查看图片异常!", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					log.error("关闭输入流异常!", e);
				}
			}
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					log.error("关闭输出流异常!", e);
				}
			bytes = null;
		}
		return null;
	}

	// setter & getter
	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public String getFiledataContentType() {
		return filedataContentType;
	}

	public void setFiledataContentType(String filedataContentType) {
		this.filedataContentType = filedataContentType;
	}

	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
}
